﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;

namespace WoltersKluwer.SPChainGang.Core.Util
{
    public static class SPDocumentLibraryHelper
    {
        /// <summary>
        /// Upload file to document library
        /// </summary>
        /// <param name="list">Document library</param>
        /// <param name="filenameToUpload">File name for upload to document library</param>
        /// <returns></returns>
        public static SPFile UploadFileToDocumetnLibrary(SPList list, string filenameToUpload)
        {
            string fileName = Path.GetFileName(filenameToUpload);
            return UploadFileToDocumetnLibrary(list, filenameToUpload, fileName);
        }

        public static SPFile UploadFileToDocumetnLibrary(SPFolder folder, string filenameToUpload)
        {
            string fileName = Path.GetFileName(filenameToUpload);
            return UploadFileToDocumetnLibrary(folder, filenameToUpload, fileName);
        }

        public static SPFile UploadFileToDocumetnLibrary(SPList list, string filenameToUpload,string fileNameInDocumentLibrary)
        {
            return UploadFileToDocumetnLibrary(list.RootFolder, filenameToUpload, fileNameInDocumentLibrary);
        }

        public static SPFile UploadFileToDocumetnLibrary(SPFolder folder, string filenameToUpload, string fileNameInDocumentLibrary)
        {
            FileStream fileStream;
            Byte[] fileContent;
            SPFile uploadedFile;

            using (fileStream = File.OpenRead(filenameToUpload))
            {
                fileContent = new byte[Convert.ToInt32(fileStream.Length)];
                fileStream.Read(fileContent, 0, Convert.ToInt32(fileStream.Length));
                uploadedFile = folder.Files.Add(folder.Url + "/" + fileNameInDocumentLibrary, fileContent, true);
                folder.ParentWeb.Lists[folder.ParentListId].Update();
            }
            return uploadedFile;
        }
    }
}
